<?php
/**
 * 用户对应关系job
 * Note:superior_code为空的话，表示没有上级
 */
apf_require_class ( 'Oa_Job_Attendance_Abstract' );
class Oa_Job_Attendance_OrgRelation extends Oa_Job_Attendance_Abstract {
	/**
	 * 考勤系统读
	 */
	private $readdb = "attendance_slave";
	/**
	 * 考勤系统写
	 */
	private $writedb = "attendance_master";
	/**
	 * 用户信息,id code superior_code
	 */
	private $user_ids;

	private static $dismission;

	public function run() {
		$this->log ( "开始检测..." );
		$user_ids = $this->get_all_ids();
		//var_dump($user_ids['DLD947']);
		//exit();
		$this->clear_db('org_relation');
		$this->alter_db('org_relation');
		//var_dump($user_ids,count($user_ids));
		foreach($user_ids as $key=>$user){
			$this->map_relation($key, $key,$user['superior_code']);
		}
		var_dump(self::$dismission);
		$this->log ( "翻译完毕..." );
	}

	/**
	 * 遍历等级关系
	 */
	public function map_relation($base_code, $user_code, $user_s_code, $level = 1) {
		// 自己是自己的上司
		if ($user_code == $user_s_code) {
			return false;
		}
		// 没有上级
		if ($user_s_code == '') {
			return false;
		}
		//所有用户信息
		$users = $this->user_ids;

		$base_id = $users[$base_code]['user_id'];
		$user_s_id = $users[$user_s_code]['user_id'];
		if($users[$user_s_code] == NULL){
			//TODO 说明上级已经离职了，记录日志
			self::$dismission[] = $user_code.",".$user_s_code;
			return false;
		}
		// 有上级，递归查找
		if ($user_s_code != '') {
			$sql = "insert into org_relation(user_id,superior_id,level) values({$base_id},{$user_s_id},{$level})";
			if ($this->execute($sql,array(),$this->writedb)) {
				echo "insert user_id {$base_id} --> user_s_id -->{$user_s_id} --> level --> {$level} ok \n";
			}
			++ $level;
			// 最多遍历十层，防止死循环
			if ($level > 10) {
				echo "死循环了...";
				// TODO邮件通知
				exit ();
			}
			$user_s_s_code = $users[$user_s_code]['superior_code'];
			@$this->map_relation ( $base_code, $user_s_code, $user_s_s_code, $level );
		}
	}

	/**
	 * 所有用户id信息
	 */
	private function  get_all_ids(){
		//都是在职的，dimission作为判断标准
		$sql = "SELECT u.user_id,u.`code`,u.superior_code FROM user_info u WHERE u.dimission_date = '0000-00-00 00:00:00'";
		$rows = $this->get_db_rows($sql, $this->readdb);
		$date = array();
		foreach ($rows as $row){
			$date[$row['code']] = array('user_id'=>$row['user_id'],'superior_code'=>$row['superior_code']);
		}
		$this->user_ids = $date;
		return $date;
	}

	/**
	 * 清空数据库
	 * @param unknown_type $db_name
	 */
	private function clear_db($db_name){
		$sql = "delete from $db_name";
		echo $sql;
		return $this->execute($sql,array(),$this->writedb);
	}

	/**
	 * 重置自增id
	 * @param unknown_type $db_name
	 */
	private function alter_db($db_name){
		$sql = "alter table $db_name AUTO_INCREMENT=1";
		return $this->execute($sql,array(),$this->writedb);
	}
}